import mss
import mss.tools
from PIL import Image
import win32gui
from core.util import time_str
import setting as c

def mss_screenshot(monitor_number, rect):
    with mss.mss() as sct:
        # Get information of monitor 2
        mon = sct.monitors[monitor_number]

        # The screen part to capture
        # monitor = {
        #     "top": mon["top"],
        #     "left": mon["left"],
        #     "width": mon["width"],
        #     "height": mon["height"],
        #     "mon": monitor_number,
        # }
        # print(monitor)
        # output = "sct-mon{mon}_{top}x{left}_{width}x{height}.png".format(**monitor)
        
        monitor = {
            "top": rect[1],
            "left": rect[0],
            "width": rect[2] - rect[0],
            "height": rect[3] - rect[1],
            "mon": monitor_number,
        }
        output = "sct-mon{mon}_{top}x{left}_{width}x{height}.png".format(**monitor)

        # Grab the data
        sct_img = sct.grab(monitor)

        # Save to the picture file
        mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
        print(output)
        return sct_img
    
def get_screenshot_image(hwnd) -> Image:
    rect = win32gui.GetWindowRect(hwnd)  
    img = mss_screenshot(2, rect) 
    rect = (rect[0], rect[1], rect[2], rect[3])
    # img = img.crop(rect)
    print(rect)
    return img

if __name__ == "__main__":
    h = 17170636
    ts = time_str()
    img_hwnd = get_screenshot_image(17170636)
    file_img = f"{c.shot_dir_path}/dm_{h}_{ts}.jpg"
    # img_hwnd.save(file_img)